Imports System.Collections
Imports System.Collections.Specialized
Imports System.Collections.Generic
Imports System.Web.UI.WebControls
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports Cdm
Imports Cdm.DataCore
Imports Cdm.AppServices
Imports Cdm.AppServices.Log
Imports Cdm.DataCore.Entities
Imports Cdm.DataCore.Custom


Partial Class Reports_ReportViewer
    Inherits System.Web.UI.Page

#Region "CONSTANTS"
    Private Const _CLASS_NAME As String = "Reports_ReportViewer"
    'Private Const _SERVER_NAME = "10.1.2.12"
#End Region

#Region "PRIVATE MEMBERS"

    Private objReport As CaseNotes.Reports
    Private reportFileName As String
    Private reportName As String
    Private reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
    Private parameterList As ArrayList

    Protected reportTitleValue As String
    Public ReadOnly Property ReportTitle() As String
        Get
            Return Me.reportTitleValue
        End Get
    End Property

#End Region

#Region "PRIVATE METHODS"
    Private Sub GetReport(ByVal reportId As Integer)

        Dim reportTitle As String

        Try

            objReport = CaseNotes.Reports.Retrieve(reportId)

            Me.reportName = objReport.ReportLongName
            reportTitle = "Reports - " & Me.reportName
            Me.Title = reportTitle
            Me.ReportNameLabel.Text = Me.reportName
            Me.reportFileName = objReport.ReportFileName

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the GetReport() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub SetCurrentValuesForParameterField(ByVal reportDocument As ReportDocument, ByVal paramName As String, ByVal value As Object)
        Try

            Dim params As ParameterValues = New ParameterValues()
            Dim paramsDiscreteValues As ParameterDiscreteValue = New ParameterDiscreteValue()
            paramsDiscreteValues.Value = value.ToString()
            params.Add(paramsDiscreteValues)

            reportDocument.DataDefinition.ParameterFields.Item(paramName).ApplyCurrentValues(params)
            If Not reportDocument.IsSubreport Then
                If Me.ReportViewer.ParameterFieldInfo.Count > 0 Then
                    Me.ReportViewer.ParameterFieldInfo.Item(paramName).CurrentValues = reportDocument.ParameterFields.Item(paramName).CurrentValues
                End If
            End If

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SetCurrentValuesForParameterField() method.", ex)
            Throw ex
        End Try
    End Sub

    Private Function ApplyLogon(ByVal reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument, ByVal conn As CrystalDecisions.Shared.ConnectionInfo) As Boolean
        ' This function is called by the "Logon" function
        ' It loops through the report tables and applies
        ' the connection information to each table.

        Try

            ' Declare the TableLogOnInfo object and a table object for use later.
            Dim tableLogonInfo As CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table

            ' For each table apply connection info.
            For Each table In reportDocument.Database.Tables
                tableLogonInfo = table.LogOnInfo
                tableLogonInfo.ConnectionInfo = conn
                table.ApplyLogOnInfo(tableLogonInfo)

                ' Verify that the logon was successful.
                ' If TestConnectivity returns false, correct table locations.
                If (table.TestConnectivity()) Then
                    ' If there is a "." in the location then remove the
                    ' beginning of the fully qualified location.
                    ' Example "dbo.northwind.customers" would become
                    ' "customers".
                    If (table.Location.IndexOf(".") > 0) Then
                        table.Location = table.Location.Substring(table.Location.LastIndexOf(".") + 1)
                    Else
                        ' If the location is not returning as a fully
                        ' qualified location we still set it to table.location
                        ' because Crystal Reports 9 installed on top of .NET
                        ' can *store* fully qualified names but will only *return*
                        ' the table name itself.
                        table.Location = table.Location
                    End If
                Else
                    Return False
                End If
            Next

            Return True

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the ApplyLogon() method.", ex)
        End Try
    End Function

    ' The Logon method iterates through all tables.
    Private Function Logon(ByVal reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument, _
        ByVal server As String, _
        ByVal database As String, _
        ByVal user_id As String, _
        ByVal password As String) As Boolean

        Try

            ' Declare and populate a new connection info object.
            Dim conn As New CrystalDecisions.Shared.ConnectionInfo()
            'Dim connItems As Array = ConfigurationManager.ConnectionStrings("SpendingPlanData").ToString().Split(";")
            Dim connItems As Array = EntityController.AppConnectString().Split(";")
            Dim connAttributes As New NameValueCollection
            For Each str As String In connItems
                If str.Trim().Length > 0 Then
                    Dim pair() As String
                    pair = str.Split("=")
                    connAttributes.Add(pair(0), pair(1))
                End If
            Next

            With conn
                .ServerName = server
                .DatabaseName = database
                .UserID = user_id
                .Password = password
            End With

            ' If the ApplyLogon function fails then return a false for this function.
            ' We are applying logon information to the main report at this stage.
            If (Not ApplyLogon(reportDocument, conn)) Then
                Return False
            End If

            ' Declare both a report object as well as a subreport object.
            Dim reportObject As CrystalDecisions.CrystalReports.Engine.ReportObject
            Dim subreportObject As CrystalDecisions.CrystalReports.Engine.SubreportObject

            ' Loop through all the report objects and locate subreports.
            ' If a subreport is found then apply logon information to
            ' the subreport.
            For Each reportObject In reportDocument.ReportDefinition.ReportObjects
                If (reportObject.Kind = CrystalDecisions.[Shared].ReportObjectKind.SubreportObject) Then
                    subreportObject = CType(reportObject, CrystalDecisions.CrystalReports.Engine.SubreportObject)
                    If (Not ApplyLogon(reportDocument.OpenSubreport(subreportObject.SubreportName), conn)) Then
                        Return False
                    End If
                End If
            Next

            ' Return True if the code runs to this stage.
            Return True

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SetParameters() method.", ex)
            Throw ex
        End Try

    End Function

    Private Sub ConfigureCrystalReports()
        Try

            Dim paramList As ArrayList = New ArrayList()
            Dim reportPath As String = Server.MapPath(Me.reportFileName)

            Me.reportDocument = New ReportDocument()
            Me.reportDocument.Load(reportPath)

            Dim connItems As Array = EntityController.AppConnectString.Split(";")
            Dim connAttributes As New NameValueCollection
            For Each str As String In connItems
                If str.Trim().Length > 0 Then
                    Dim pair() As String
                    pair = str.Split("=")
                    connAttributes.Add(pair(0), pair(1))
                End If
            Next

            Me.reportDocument.SetDatabaseLogon(connAttributes("User ID"), connAttributes("Password"), connAttributes("Data Source"), connAttributes("Initial Catalog"))
            If Me.Logon(Me.reportDocument, connAttributes("Data Source"), connAttributes("Initial Catalog"), connAttributes("User ID"), connAttributes("Password")) Then

                'If Me.reportName.ToString().ToUpper() = "BATCH MONTHLY STATEMENT REPORT" Then
                'Me.BatchPrintMonthlyStatementReport()
                'Else
                ReportViewer.ReportSource = reportDocument
                Me.SetParameters()
                'End If

            End If

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the ConfigureCrystalReports() method.", ex)
            Throw ex
        End Try
    End Sub
    Private Sub BatchPrintMonthlyStatementReport()
        Dim t_ParticipantList As List(Of ParticipantDisplay) = Cdm.DataCore.Custom.ParticipantDisplay.ListByFMSAUserID(Session("CurrentUserId"), "LastName", True)
        Dim t_Participant As ParticipantDisplay
        Dim t_ExpenditureReportId As String

        Dim sqlDataSource As New SqlDataSource
        Dim parmParticipantId As New Parameter
        Dim args As New DataSourceSelectArguments
        Dim iReportCount As Int32 = 0

        For Each t_Participant In t_ParticipantList
            sqlDataSource.ConnectionString = EntityController.AppConnectString
            sqlDataSource.SelectCommand = "spGetExpenditureReports"
            sqlDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure

            parmParticipantId.Name = "ParticipantId"
            parmParticipantId.Type = TypeCode.Int32
            parmParticipantId.DefaultValue = t_Participant.ParticipantId

            If iReportCount = 0 Then
                sqlDataSource.SelectParameters.Add(parmParticipantId)
            End If

            Dim dv As System.Data.DataView = sqlDataSource.Select(args)
            'dv.RowFilter = "EffectiveDates"
            If dv.Count <> 0 Then
                t_ExpenditureReportId = dv.Item(0).Item("ExpenditureReportId").ToString()

                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@ParticipantId", t_Participant.ParticipantId.ToString())
                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@vExpenditureReportId", t_ExpenditureReportId)
                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@vExpenditureReportId1", t_ExpenditureReportId)
                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@vExpenditureReportId", t_ExpenditureReportId)
                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@vExpenditureReportId", t_ExpenditureReportId)
                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@vExpenditureReportId", t_ExpenditureReportId)
                Me.SetCurrentValuesForParameterField(Me.reportDocument, "@vExpenditureReportId", t_ExpenditureReportId)

                Me.reportDocument.PrintToPrinter(1, False, 0, 0)

            End If
            iReportCount = iReportCount + 1
        Next
    End Sub

    Private Sub SetParameters()
        Try

            Select Case (Me.reportName.ToUpper())
                Case "BATCH MONTHLY STATEMENT REPORT", "MASTER PARTICIPANT LIST"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
               Case "IN HOME MONITORING PAST DUE BY 30 DAYS OR MORE"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@daysPastDue", 30)
                Case "MONTHLY SPENDING REPORT"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@AsOfDate", Me.DateTimeControlDate.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginMonth", Me.DropDownControlBeginMonth.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginYear", Me.TextBeginYear.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endMonth", Me.DropDownControlEndMonth.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endYear", Me.TextEndYear.Value)
                Case "APPEAL TRACKING REPORT"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@noteType", "Appeal")
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginDate", Me.BeginDateInputControl.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endDate", Me.EndDateInputControl.Value)
                Case "GRIEVANCE TRACKING REPORT"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@noteType", "Grievance")
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginDate", Me.BeginDateInputControl.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endDate", Me.EndDateInputControl.Value)
                Case "INCIDENT TRACKING REPORT"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@noteType", "Incident")
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginDate", Me.BeginDateInputControl.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endDate", Me.EndDateInputControl.Value)
                Case "IN HOME MONITORING - BY DUE DATE REPORT", "LIST OF SUPPORT BROKERS BY AGENCY"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                Case "MONTHLY SPENDING - LESS THAN %"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Percentage", Me.TextInputControlPercent.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@isGreaterThan", False)
                    'Me.SetCurrentValuesForParameterField(Me.reportDocument, "@AsOfDate", Me.DateTimeControlDate.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginMonth", Me.DropDownControlBeginMonth.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginYear", Me.TextBeginYear.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endMonth", Me.DropDownControlEndMonth.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endYear", Me.TextEndYear.Value)
                Case "MONTHLY SPENDING - GREATER THAN %"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Percentage", Me.TextInputControlPercent.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@isGreaterThan", True)
                    'Me.SetCurrentValuesForParameterField(Me.reportDocument, "@AsOfDate", Me.DateTimeControlDate.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginMonth", Me.DropDownControlBeginMonth.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@beginYear", Me.TextBeginYear.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endMonth", Me.DropDownControlEndMonth.Value)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@endYear", Me.TextEndYear.Value)
                Case "ASSESSMENTS PAST DUE BY 30 OR MORE DAYS"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Month", Me.DropDownControlMonth.SelectedValue.ToString())
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Year", Me.TextInputControlYear.Value.ToString())
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@NumOfDays", 30)
                Case "ASSESSMENTS BY DUE DATE", _
                    "PARTICIPANTS BY DOLLAR AMOUNT OF SAVINGS PLAN GOAL", _
                    "PARTICIPANTS BY % OF BUDGET IN SAVINGS PLAN", _
                    "PARTICIPANTS BY DOLLAR AMOUNT SAVED IN SAVINGS", _
                    "PARTICIPANTS BY % OF SAVINGS GOAL ACCUMULATED", _
                    "PARTICIPANTS WITH MORE THAN 100% OF SAVINGS GOAL ACCUMULATED BUT NO PURCHASE MADE", _
                    "PERCENT OF ENROLLEES WHO HAD NOT RECEIVED SERVICES", _
                    "DETAIL ON REASONS FOR DISENROLLMENT", _
                    "ENROLLMENT/DISENROLLMENT - CUMULATIVE THROUGH CURRENT MONTH", _
                    "ENROLLMENT/DISENROLLMENT IN EACH OF THE LAST 12 MONTHS", _
                    "ENROLLMENT TO FIRST SERVICES"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Month", Me.DropDownControlMonth.SelectedValue.ToString())
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Year", Me.TextInputControlYear.Value.ToString())
                Case "RECIPIENTS OF SERVICES UNDER A CAST & COUNSELING BUDGET AND DROPOUTS", _
                    "ENROLLMENT BY REFERRAL PROGRAM"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Quarter", Me.DropDownInputControlQuarter.SelectedValue.ToString())
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@Year", Me.TextInputControlYear.Value.ToString())
                Case "DEMOGRAPHIC CHARACTERISTICS OF PARTICIPANTS", _
                    "AMOUNT OF MONTHLY BUDGET", _
                    "MONTHLY STATEMENT SUMMARY REPORT"
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@userId", UserAuthorization.CurrentUser.UserId)
                    Me.SetCurrentValuesForParameterField(Me.reportDocument, "@AsOfDate", Me.DateTimeControlDate.Value)

            End Select

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SetParameters() method.", ex)
            Throw ex
        End Try
    End Sub

    Private Function HasParameters() As Boolean

        Try

            Select Case (Me.reportName.ToUpper())
                Case "IN HOME MONITORING - BY DUE DATE REPORT", _
                    "IN HOME MONITORING PAST DUE BY 30 DAYS OR MORE", _
                    "BATCH MONTHLY STATEMENT REPORT", _
                    "LIST OF SUPPORT BROKERS BY AGENCY", _
                    "LIST OF SUPPORT BROKER AGENCIES", _
                    "MASTER PARTICIPANT LIST"
                    Return False
                Case Else
                    Return True
            End Select

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the HasParameters() method.", ex)
            Throw ex
        End Try

    End Function

    Private Sub FillMonths()

        Try

            Dim lcv As Integer

            For lcv = 1 To 12
                Me.DropDownControlMonth.Items.Add(New ListItem(MonthName(lcv), lcv))
                Me.DropDownControlBeginMonth.Items.Add(New ListItem(MonthName(lcv), lcv))
                Me.DropDownControlEndMonth.Items.Add(New ListItem(MonthName(lcv), lcv))
            Next

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the FillMonths() method.", ex)
            Throw ex
        End Try

    End Sub

    Public Sub FillQuarters()

        Try

            Me.DropDownInputControlQuarter.Items.Add(New ListItem("1st Quarter", 1))
            Me.DropDownInputControlQuarter.Items.Add(New ListItem("2nd Quarter", 2))
            Me.DropDownInputControlQuarter.Items.Add(New ListItem("3rd Quarter", 3))
            Me.DropDownInputControlQuarter.Items.Add(New ListItem("4th Quarter", 4))

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the FillQuarters() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub ResetInputs()

        Try

            Me.DropDownControlMonth.SelectedIndex = 0
            Me.DropDownInputControlQuarter.SelectedIndex = 0

            Me.TextInputControlPercent.Value = String.Empty
            Me.TextInputControlYear.Value = String.Empty

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the ClearInputs() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub DisplayParameters()

        Try

            Me.FillMonths()
            Me.FillQuarters()

            Select Case (Me.reportName.ToUpper())
                'MONTH, YEAR
                Case "ASSESSMENTS BY DUE DATE", _
                    "ASSESSMENTS PAST DUE BY 30 OR MORE DAYS", _
                    "PERCENT OF ENROLLEES WHO HAD NOT RECEIVED SERVICES", _
                    "DETAIL ON REASONS FOR DISENROLLMENT", _
                    "ENROLLMENT/DISENROLLMENT - CUMULATIVE THROUGH CURRENT MONTH", _
                    "ENROLLMENT/DISENROLLMENT IN EACH OF THE LAST 12 MONTHS", _
                    "ENROLLMENT TO FIRST SERVICES", _
                    "PARTICIPANTS BY DOLLAR AMOUNT OF SAVINGS PLAN GOAL", _
                    "PARTICIPANTS BY % OF BUDGET IN SAVINGS PLAN", _
                    "PARTICIPANTS BY DOLLAR AMOUNT SAVED IN SAVINGS", _
                    "PARTICIPANTS WITH MORE THAN 100% OF SAVINGS GOAL ACCUMULATED BUT NO PURCHASE MADE", _
                    "PARTICIPANTS BY % OF SAVINGS GOAL ACCUMULATED"
                    Me.rowPercent.Visible = False
                    Me.rowDate.Visible = False
                    Me.rowQuarter.Visible = False
                    Me.rowMonth.Visible = True
                    Me.rowYear.Visible = True
                    Me.rowButtons.Visible = True
                    Me.rowBeginDate.Visible = False
                    Me.rowEndDate.Visible = False
                    Me.rowBeginMonthAndYear.Visible = False
                    Me.rowEndMonthAndYear.Visible = False
                    Me.ParameterDescriptionLabel.Text = "Report will be run as of last day of the selected month."
                    'QUARTER, YEAR
                Case "RECIPIENTS OF SERVICES UNDER A CAST & COUNSELING BUDGET AND DROPOUTS", _
                    "ENROLLMENT BY REFERRAL PROGRAM"
                    Me.rowPercent.Visible = False
                    Me.rowDate.Visible = False
                    Me.rowEndDate.Visible = False
                    Me.rowBeginDate.Visible = False
                    Me.rowQuarter.Visible = True
                    Me.rowMonth.Visible = False
                    Me.rowYear.Visible = True
                    Me.rowButtons.Visible = True
                    Me.rowBeginMonthAndYear.Visible = False
                    Me.rowEndMonthAndYear.Visible = False
                    Me.ParameterDescriptionLabel.Text = "Report will show enrollment data as of the last day of the selected quarter."
                    'DATETIME
                Case "DEMOGRAPHIC CHARACTERISTICS OF PARTICIPANTS", _
                    "AMOUNT OF MONTHLY BUDGET", "MONTHLY STATEMENT SUMMARY REPORT"
                    Me.rowPercent.Visible = False
                    Me.rowQuarter.Visible = False
                    Me.rowMonth.Visible = False
                    Me.rowYear.Visible = False
                    Me.rowDate.Visible = True
                    Me.rowButtons.Visible = True
                    Me.rowBeginDate.Visible = False
                    Me.rowEndDate.Visible = False
                    Me.rowBeginMonthAndYear.Visible = False
                    Me.rowEndMonthAndYear.Visible = False
                    Me.ParameterDescriptionLabel.Text = "Report will show current data as of the date selected below."
                Case "MONTHLY SPENDING - LESS THAN %", _
                "MONTHLY SPENDING - GREATER THAN %"
                    Me.rowPercent.Visible = True
                    Me.rowQuarter.Visible = False
                    Me.rowMonth.Visible = False
                    Me.rowYear.Visible = False
                    Me.rowDate.Visible = False
                    Me.rowButtons.Visible = True
                    Me.rowEndDate.Visible = False
                    Me.rowBeginDate.Visible = False
                    Me.rowBeginMonthAndYear.Visible = True
                    Me.rowEndMonthAndYear.Visible = True
                    Me.ParameterDescriptionLabel.Text = "Report on spending as of selected date, and outside selected percentage."
                Case "MONTHLY SPENDING REPORT"
                    Me.rowPercent.Visible = False
                    Me.rowQuarter.Visible = False
                    Me.rowMonth.Visible = False
                    Me.rowYear.Visible = False
                    Me.rowDate.Visible = False
                    Me.rowButtons.Visible = True
                    Me.rowEndDate.Visible = False
                    Me.rowBeginDate.Visible = False
                    Me.rowBeginMonthAndYear.Visible = True
                    Me.rowEndMonthAndYear.Visible = True
                    Me.ParameterDescriptionLabel.Text = "Report on spending within selected Date Range"

                Case "APPEAL TRACKING REPORT", "GRIEVANCE TRACKING REPORT", "INCIDENT TRACKING REPORT"
                    Me.rowPercent.Visible = False
                    Me.rowQuarter.Visible = False
                    Me.rowMonth.Visible = False
                    Me.rowYear.Visible = False
                    Me.rowDate.Visible = False
                    Me.rowButtons.Visible = True
                    Me.rowEndDate.Visible = True
                    Me.rowBeginDate.Visible = True
                    Me.rowBeginMonthAndYear.Visible = False
                    Me.rowEndMonthAndYear.Visible = False
                    Me.ParameterDescriptionLabel.Text = "Enter date range for notes to display."

            End Select
            If Not Me.IsPostBack Then
                SetParameterDefaults()
                SetRowBackgroundColors()
            End If
        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the DisplayParameters() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub SetParameterDefaults()
        Dim previousQuarter As String = "", previousQuarterYear As String = ""
        Me.DateTimeControlDate.Value = System.DateTime.Now.ToString
        Me.DropDownControlMonth.Value = Month(System.DateTime.Now).ToString()
        GetPreviousQuarterEnd(previousQuarter, previousQuarterYear)
        Me.DropDownInputControlQuarter.Value = previousQuarter
        Me.EndDateInputControl.Value = System.DateTime.Now.ToString
        Me.BeginDateInputControl.Value = DateAdd(DateInterval.Month, -1, System.DateTime.Now).ToString
        Me.DropDownControlBeginMonth.Value = Month(DateAdd(DateInterval.Month, -1, System.DateTime.Now)).ToString
        Me.DropDownControlEndMonth.Value = Month(System.DateTime.Now).ToString
        Me.TextBeginYear.Value = Year(DateAdd(DateInterval.Month, -1, System.DateTime.Now)).ToString
        Me.TextEndYear.Value = Year(System.DateTime.Now).ToString
        If rowQuarter.Visible = True Then
            Me.TextInputControlYear.Value = previousQuarterYear
        Else
            Me.TextInputControlYear.Value = Year(Now).ToString()
        End If
    End Sub

    Private Sub SetRowBackgroundColors()
        Dim isWhiteBackground As Boolean = True
        isWhiteBackground = SetRow(Me.rowPercent, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowQuarter, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowMonth, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowBeginMonthAndYear, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowEndMonthAndYear, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowYear, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowDate, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowBeginDate, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowEndDate, isWhiteBackground)
        isWhiteBackground = SetRow(Me.rowButtons, isWhiteBackground)
    End Sub

    Private Function SetRow(ByVal row As HtmlTableRow, ByVal isWhite As Boolean) As Boolean
        If row.Visible Then
            If isWhite Then
                row.Style("background-color") = "#ffffff"
            Else
                row.Style("background-color") = "#E8ECF4;"
            End If
            Return Not isWhite
        Else
            Return isWhite
        End If

    End Function

    ''' <summary>
    ''' If this is the last day of the quarter, use this quarter
    ''' otherwise, populate the quarter and year of the previous quarter
    ''' </summary>
    ''' <param name="qtrValue"></param>
    ''' <param name="yrValue"></param>
    ''' <remarks></remarks>
    Private Sub GetPreviousQuarterEnd(ByRef qtrValue As String, ByRef yrValue As String)
        Dim dtLastQuarter As System.DateTime
        dtLastQuarter = DateAdd(DateInterval.Day, 1, System.DateTime.Now)
        dtLastQuarter = DateAdd(DateInterval.Quarter, -1, dtLastQuarter)
        qtrValue = Convert.ToString(Int(Month(dtLastQuarter) / 4) + 1)
        yrValue = Year(dtLastQuarter).ToString
    End Sub

#End Region

#Region "EVENT HANDLERS"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim userID As Integer = UserAuthorization.CurrentUser.UserId
        Dim reportID As Integer = -1

        Try

            reportID = CType(Request.QueryString.Get("reportId"), Integer)

            Me.GetReport(reportID)

            If Not Me.IsPostBack Then

                Me.AppNameLabel.Text = Application("AppName")
                Me.DeptNameLabel.Text = Application("StateDeptName")
                If Me.HasParameters() Then

                    Me.DisplayParameters()

                Else

                    Me.rowQuarter.Visible = False
                    Me.rowMonth.Visible = False
                    Me.rowYear.Visible = False
                    Me.rowDate.Visible = False
                    Me.rowButtons.Visible = False

                    'SET THE REPORT PARAMS
                    Me.ConfigureCrystalReports()

                End If

            Else

                'SET THE REPORT PARAMS
                Me.ConfigureCrystalReports()

            End If


        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the Page_Load() method.", ex)
        End Try

    End Sub

#End Region


    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Me.ReportViewer.Dispose()
    End Sub
End Class
